﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevComponents.DotNetBar;

namespace QLThuChi.OtherForms
{
    #region Using
    using QLThuChi.Helpers;
    using QLThuChi.Models;
    using QLThuChi.Repositories;
    using System.Globalization;
    #endregion

    /// <summary>
    /// tuansl added: manage loai don vi corresponding with menus in app
    /// </summary>
    public partial class FrmQuanLyNhanCongGiaiDoan: Office2007Form
    {
        public EventHandler Handler { get; set; }
        private bool Updated = false;
        private EnumUpdateMode UpdateMode = EnumUpdateMode.INSERT;
        // Hidden files are used to store ids 
        private DevComponents.DotNetBar.Controls.TextBoxX txtMaCongTrinhGiaiDoan;

        public FrmQuanLyNhanCongGiaiDoan(int macongtrinhgiaidoan)
        {
            InitializeComponent();
            InitHiddenFields();

            txtMaCongTrinhGiaiDoan.Text = macongtrinhgiaidoan.ToString();
            var giaidoan = CongTrinh_GiaiDoanRepository.SelectByID(int.Parse(txtMaCongTrinhGiaiDoan.Text));
            txtCongTrinh.Text = giaidoan.CongTrinh.TenCongTrinh;
            txtGiaiDoan.Text = giaidoan.GiaiDoan.TenGiaiDoan;
        }

        public void InitHiddenFields()
        {
            // Add a new textbox
            txtMaCongTrinhGiaiDoan = new DevComponents.DotNetBar.Controls.TextBoxX
            {
                Name = "txtMaCongTrinhGiaiDoan",
                Text = ""
            };
            txtMaCongTrinhGiaiDoan.Visible = false;
        }

        private void btnChonCongTrinh_Click(object sender, EventArgs e)
        {
            FrmQuanLyCongTrinh frm = new FrmQuanLyCongTrinh();
            frm.Handler += GetCongTrinh;
            frm.ShowDialog();
        }

        public void GetCongTrinh(object sender, EventArgs e)
        {
            var eventType = (MyEvent)e;
            string[] comp = eventType.Data.Split(new char[] { '#' });

            txtMaCongTrinhGiaiDoan.Text = comp[0];
            txtCongTrinh.Text = comp[1];

            LoadData();
        }

        private void btnThemVaoDanhSach_Click(object sender, EventArgs e)
        {
            FrmQuanLyNhanCong frm = new FrmQuanLyNhanCong(true);
            frm.Handler += GetNhanCong;
            frm.ShowDialog();
        }

        public void GetNhanCong(object sender, EventArgs e)
        {
            var eventType = (MyEvent)e;
            string[] comp = eventType.Data.Split(new char[] { '#' });

            var item = NhanCongRepository.SelectByID(int.Parse(comp[0]));

            ListViewItem objListViewItem = new ListViewItem();
            objListViewItem.Tag = item;
            objListViewItem.Text = comp[0];
            objListViewItem.SubItems.Add(item.TenNhanCong);
            objListViewItem.SubItems.Add(item.LoaiNhanCong.TenLoaiNhanCong);
            objListViewItem.SubItems.Add(item.BoPhan.TenBoPhan);
            lstvData.Items.Add(objListViewItem);
        }

        private void btnXoaKhoiDanhSach_Click(object sender, EventArgs e)
        {
            if (lstvData.SelectedItems.Count > 0)
            {
                lstvData.Items.RemoveAt(lstvData.SelectedIndices[0]);
            }
        }

        public bool ValidateUserInput(ref string errorText)
        {
            if (lstvData.Items.Count == 0)
            {
                errorText = "Danh sách hiện thời không có gì!";
                return false;
            }
            return true;
        }

        private void btnGhi_Click(object sender, EventArgs e)
        {
            string errorText = "";
            bool success = false;

            if (!ValidateUserInput(ref errorText))
            {
                MessageBoxEx.Show(errorText, "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (ActionUpdate())
            {
                success = true;
            }

            if (success)
            {
                MessageBoxEx.Show("Cập nhật dữ liệu thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                MessageBoxEx.Show("Cập nhật dữ liệu thất bại", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        public bool CheckingIsExist(int congtrinhgiaidoan, int nhancong)
        {
            var lst = GiaiDoan_NhanCongRepository.SelectByMaCongTrinhGiaiDoan(congtrinhgiaidoan);
            for (int i = 0; i < lst.Count; i++)
            {
                if (lst[i].MaNhanCong == nhancong)
                {
                    return true;
                }
            }
            return false;
        }

        private bool ActionUpdate()
        {
            try
            {
                // Open connection
                DataContext.Instance.Connection.Open();
                // Define a transaction for the operations
                using (var transaction = DataContext.Instance.Connection.BeginTransaction())
                {
                    // Remove all tour dia diem
                    // Add new all tour diadiem
                    for (int i = 0; i <= lstvData.Items.Count - 1; i++)
                    {
                        var culture = CultureInfo.CreateSpecificCulture("vi");
                        var ctgd = new GiaiDoan_NhanCong
                        {
                            MaNhanCong = int.Parse(lstvData.Items[i].Text),
                            MaCongTrinhGiaiDoan = int.Parse(txtMaCongTrinhGiaiDoan.Text)
                        };
                        if (!CheckingIsExist(ctgd.MaCongTrinhGiaiDoan.Value, ctgd.MaNhanCong.Value))
                        {
                            if (!GiaiDoan_NhanCongRepository.Insert(ctgd))
                            {
                                return false;
                            }
                        }
                    }
                    // Mark the transaction as complete
                    transaction.Commit();
                    DataContext.Instance.Connection.Close();
                }
                return true;
            }
            catch
            {
                return false;
            }
        }

        private void btnThoat_Click(object sender, EventArgs e)
        {
            Close();
        }

        public void LoadData()
        {
            var lstItem = GiaiDoan_NhanCongRepository.SelectByMaCongTrinhGiaiDoan(int.Parse(txtMaCongTrinhGiaiDoan.Text));
            lstvData.Items.Clear();
            if (lstItem.Count > 0)
            {
                for (int i = 0; i <= lstItem.Count - 1; i++)
                {
                    ListViewItem objListViewItem = new ListViewItem();
                    objListViewItem.Tag = lstItem[i];
                    objListViewItem.Text = lstItem[i].MaNhanCong.ToString();
                    objListViewItem.SubItems.Add(lstItem[i].NhanCong.TenNhanCong);
                    objListViewItem.SubItems.Add(lstItem[i].NhanCong.LoaiNhanCong.TenLoaiNhanCong);
                    objListViewItem.SubItems.Add(lstItem[i].NhanCong.BoPhan.TenBoPhan);
                    lstvData.Items.Add(objListViewItem);
                }
            }
        }

        private void FrmQuanLyNhanCongGiaiDoan_Load(object sender, EventArgs e)
        {
            LoadData();
        }
    }
}